package com.ku.order.service.impl;

//import com.ku.constants.OrderStatus;

import cn.hutool.core.util.IdUtil;
import cn.hutool.db.handler.HandleHelper;
import cn.hutool.json.JSONUtil;
import com.ku.constants.OrderStatus;
import com.ku.entity.Order;
import com.ku.order.mapper.OrderMapper;
import com.ku.order.service.mq.OrderlyProducer;
import com.ku.service.OrderService;
import com.ku.service.StoreService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @program: rocketMQKill
 * @description:
 * @author: JokerKu
 * @create: 2020-05-04 17:00
 **/
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Reference
    private StoreService storeService;

    @Autowired
    private OrderlyProducer orderlyProducer;

    public static final String PKG_TOPIC = "pkg_topic";
    public static final String PKG_TAGS = "pkg_tag";


    @Override
    public String test(String name) {
        System.out.println("name:" + name);
        return name;
    }

    @Transactional
    @Override
    public boolean createOrder(String cityId, String platformId, String userId, String supplierId, String goodsId) {
        boolean flag = false;
        try {
            //创建订单
            Order order = new Order();
            order.setOrderId(UUID.randomUUID().toString().substring(0, 32));
            order.setOrderType("1");
            order.setCityId(cityId);
            order.setPlatformId(platformId);
            order.setUserId(userId);
            order.setSupplierId(supplierId);
            order.setGoodsId(goodsId);
            order.setOrderStatus(OrderStatus.ORDER_CREATED.getValue());
            order.setRemark("");

            Date currentTime = new Date();
            order.setCreateBy("admin");
            order.setCreateTime(currentTime);
            order.setUpdateBy("admin");
            order.setUpdateTime(currentTime);

            //扣减库存：
            //1.查询当前版本号
            int version = storeService.selectVersion(supplierId, goodsId);
            //2.库存
            int result = storeService.updateStoreCountByVersion(version, supplierId, goodsId, "admin", currentTime);
            //判断库存是否扣减成功 然后生成订单
            if (result == 1) {
                //todo :如果出现sql异常，订单入库失败，那么需要对库存数量和版本号进行回滚
                orderMapper.insertSelective(order);
                flag = true;
            }
            //没有更新成功，分两种情况：1.高并发乐观锁生效 2.库存不足
            else if (result == 0) {
                //判断是什么情况造成的
                int storeCount = storeService.selectStoreCount(supplierId, goodsId);
                //是由库存不足造成的：
                if (storeCount == 0) {
                    //告诉前端库存不足... {flag:false,messageCode:003,message:当前库存不足}
                    System.err.println("下单失败：库存不足....");
                } else {
                    //告诉前端操作失败... {flag:false,messageCode:004,message:操作失败请重试}
                    System.err.println("下单失败：乐观锁生效....");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            //打日志
            //捕获具体的异常进行处理
        }


        return flag;
    }

    @Override
    public String selectOrderStatus(String orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        return order.getOrderStatus();
    }

    @Override
    public int updateOrderStatus(String orderId, OrderStatus orderPayed) {
        Order order = new Order();
        order.setOrderStatus(orderPayed.getValue());
        return orderMapper.updateByPrimaryKeySelective(order);
    }


    /**
     * 顺序消息
     * @param userId
     * @param orderId
     */
    @Override
    public void sendOrderlyMessageForPkg(String userId, String orderId) {
        List<Message> messagesList = new ArrayList<>();
        //封装消息参数
        //------message1-------
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("orderId", orderId);
        params.put("desc", "步骤1---创建包裹操作");
        final String KEYS = IdUtil.simpleUUID();
        Message message = new Message(PKG_TOPIC, PKG_TAGS, KEYS, JSONUtil.toJsonStr(params).getBytes());
        messagesList.add(message);

        //------message2-------
        //封装消息参数
        Map<String, Object> params2 = new HashMap<>();
        params2.put("userId", userId);
        params2.put("orderId", orderId);
        params2.put("desc", "步骤2---发送物流通知");
        final String KEYS2 = IdUtil.simpleUUID();
        Message message2 = new Message(PKG_TOPIC, PKG_TAGS, KEYS2, JSONUtil.toJsonStr(params2).getBytes());
        messagesList.add(message2);

        //顺序消息投递 应该按照供应商ID 与topic 和 messageQueueId 进行绑定对应
        //这里模拟情况下，数据库表字段中的supplier_id 对应供应商ID
        Order order = orderMapper.selectByPrimaryKey(orderId);
        int messageQueueNumber = Integer.parseInt(order.getSupplierId());

        //对应的顺序消息的生产者 把messageList 发出去
        orderlyProducer.sendOrderlyMessage(messagesList, messageQueueNumber);
    }
}
